<?php

namespace App\Http\Controllers\Backend;

use App\Feedback;
use App\Http\Util\Common;
use App\Photo;
use App\Type;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FeedbackController extends BaseController
{
    public function __construct(Feedback $model)
    {
        $this->model = $model;
        $this->view = 'feedback';
        $this->title = 'Testimonials';
        $this->baseModel = Feedback::class;
    }

    public function index()
    {
        $review = request()->get('review');
        $title = $this->title;
        return view('backend.'.$this->view.'.index',compact('title','review'));
    }

    public function validateStore($request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'content' => 'required',
            'file' => 'file'
        ]);
        $data = $request->all();

        if($request->hasFile('file')) {
            $file = $request->file('file');
            $bool = Common::upload($file);
            unset($data['file']);

            if ($bool) {
                $data['image'] = $bool;
                return $data;
            } else {
                throw new \Exception('file upload fail');
            }
        }
        return $data;
    }

    public function store(Request $request)
    {
        $data = $this->validateStore($request);
        $order = array("\r\n", "\n", "\r");
        $replace = '<br>';

        $data['content'] = str_replace($order, $replace, $data['content']);
        Feedback::create($data);
        return redirect()->back();
    }

    public function update(Request $request, $model)
    {
        $data = $this->validateUpdate($request);
        if($request->hasFile('file')) {
            Storage::disk('public_uploads')->delete($model->image);
        }
        $order = array("\r\n", "\n", "\r");
        $replace = '<br>';

        $data['content'] = str_replace($order, $replace, $data['content']);
        $model->update($data);
        return redirect()->back();
    }


    public function review($model)
    {
        $model->review = true;
        $model->save();
        return redirect()->back();
    }

    public function showAll()
    {
        $data = request()->all();
        $feedback = Feedback::where('review',$data['review']);
        $total = $feedback->count();
        $feedback = $feedback->skip($data['offset'])->limit($data['limit'])->get();
        return response()->json([
            'status' => 0,
            'data' => [
                'data' => $feedback,
                'total' => $total
            ]
        ]);
    }

}
